
// https://leetcode.cn/problems/flood-fill/description/

class Solution
{
    int old_color;
    int m, n;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };

public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color)
    {
        if (image[sr][sc] == color) return image;
        old_color = image[sr][sc];
        m = image.size();
        n = image[0].size();
        dfs(image, sr, sc, color);
        return image;
    }

    void dfs(vector<vector<int>>& image, int i, int j, int color)
    {
        if (image[i][j] != old_color)
            return;

        image[i][j] = color;
        for (int k = 0; k < 4; ++k)
        {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n)
                dfs(image, x, y, color);
        }
    }
};